package com.telit.android.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.telit.android.dto.GisPointDto;
import com.telit.android.entity.PatrolWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 远程服务调用封装
 */
@Service
@Component
@Slf4j
public class RemoteServiceProvider {

    private static final String USER_ID_BATCH_TEMPLATE = "userid in (%s)";

   // @Value("${gis.point.url:https://gis.ahtelit.com/server/rest/services/yichang/patrol_point/FeatureServer/0}")
    @Value("${gis.point.url}")
    private String gisUrl;

    /**
     * 发送点位信息到gis服务
     */
    public void pushWorkerPosition(List<PatrolWorker> workers) {

        List<Long> workerIds = workers.stream().map(PatrolWorker::getUserId).collect(Collectors.toList());
        Map<Long, GisPointDto.Attributes> gisPointMap = queryPoint(workerIds);

        List<GisPointDto> updateList = new ArrayList<>();
        List<GisPointDto> addList = new ArrayList<>();
        workers.forEach(workerInfo -> {
            GisPointDto gisPointDto = new GisPointDto();
            gisPointDto.applyGeometry(workerInfo.getLongitude(), workerInfo.getLatitude());
            GisPointDto.Attributes attributes = gisPointMap.get(workerInfo.getUserId());

            if (Objects.nonNull(attributes)) {// 更新
                attributes.setState(workerInfo.getOnline());
                if (StrUtil.isEmpty(attributes.getType())) {
                    attributes.setType(workerInfo.getPatrolType().toString());
                }
                gisPointDto.setAttributes(attributes);
                updateList.add(gisPointDto);
            } else { // 新增
                attributes = new GisPointDto.Attributes();
                attributes.setState(workerInfo.getOnline());
                attributes.setType(workerInfo.getPatrolType().toString());
                attributes.setUserid(workerInfo.getUserId().toString());
                gisPointDto.setAttributes(attributes);
                addList.add(gisPointDto);
            }
        });

        if (updateList.size() > 0) {
            doUpdatePoint(updateList, false);
        }

        if (addList.size() > 0) {
            doUpdatePoint(addList, true);
        }

    }

    /**
     * 查询用户gis信息
     */
    private Map<Long, GisPointDto.Attributes> queryPoint(List<Long> userIds) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("returnGeometry", false);
        queryMap.put("outFields", "*");
        queryMap.put("f", "json");

        String userIdStr = userIds.stream().map(id -> "'" + id + "'").collect(Collectors.joining(","));
        queryMap.put("where", String.format(USER_ID_BATCH_TEMPLATE, userIdStr));
        log.info("查询gis点位信息，传参：{}", queryMap);
        String res = HttpUtil.get(gisUrl + "query", queryMap);
        log.info("查询gis点位信息，结果：{}", res);
        JSONObject wrapper = JSONUtil.parseObj(res);
        JSONArray features = wrapper.getJSONArray("features");
        return features.stream().map(obj -> {
            JSONObject jsonObject = (JSONObject) obj;
            return jsonObject.get("attributes", GisPointDto.Attributes.class);
        }).collect(Collectors.toMap(o -> Long.valueOf(o.getUserid()), o -> o));
    }

    private void doUpdatePoint(List<GisPointDto> pointDtos, boolean add) {
        String action = add ? "addFeatures" : "updateFeatures";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("f", "json");
        paramMap.put("features", JSONUtil.toJsonStr(pointDtos));
        log.info("更新gis点位信息，传参：{}", paramMap);
        String res = HttpUtil.post(gisUrl + action, paramMap);
        log.info("更新gis点位信息，结果：{}", res);
    }


}
